import Qs from 'qs'
import axios from 'axios'
import { Message } from 'element-ui'

// 创建axios实例
axios.defaults.withCredentials = false
const service = axios.create({
  timeout: 30000, // 请求超时时间
  // baseURL: `http://xinzhi_school.jsyixin.com/`, // ?TODO 根据部署环境修改域名
  // baseURL: `http://www.xzjs.com/`, // ?TODO 根据部署环境修改域名
  // baseURL: `https://school.jsyixin.com/`,
  baseURL: ``,
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }]
})

// request请求拦截器
service.interceptors.request.use(config => {
  // config.url = config.url.replace(/\/api/, '')
  if (!config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  }
  let token = window.sessionStorage.getItem('token')
  if (token) {
    config.headers.token = `${token}`
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// respone响应拦截器
service.interceptors.response.use(response => {
  let result
  if (response.data.errCode === 10008) {
    window.location.href = '/'
    result = response
  } else {
    result = response
  }
  return result
}, error => {
  Message.error(error.msg)
  return Promise.reject(error)
})

export default service
